//app.js
var req = require("./utils/action.js");
var utils = require("./utils/util.js");
App({
  onLaunch: function (options) {
    wx.setStorageSync('selected', 0)
    console.log(options)
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明：
        //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境（第一个创建的环境）
        // env: 'my-env-id',
        traceUser: true,
      })
    }
    this.globalData = {}

    // --------------------------------新版本------------------------------------
    this.getSystemInfo();
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    let customerId = wx.getStorageSync('customerId');
    //sessionKey = ''
    if(customerId != '' && customerId != null){
      let r = {customerId:customerId},_url = req.actions.ym+"customer/login",that = this
      this.globalData.userInfo = wx.getStorageSync('customerInfo')
      console.log("this.globalData.userInfo",this.globalData.userInfo)
      utils.getAction(r,_url,function(res){
        console.log("customer/login:",res.data.content)
        if(res.data.code == '200'){
          that.loginSuccess(that.campus.page,that.campus.type)
          that.globalData.userInfo = res.data.content;
          that.globalData.userInfo.img = req.actions.fileRoot + that.globalData.userInfo.img
          wx.setStorageSync('customerId', that.globalData.userInfo.id)
          wx.setStorageSync('customerInfo', that.globalData.userInfo)
        }else{
          that.login()
        }
      });
    }else{
      this.login()
    }
     // 导航栏数据
     wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;  
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
      }
    })
  },
  setCallBack:function(type,callback,obj){
    if(type == 'menuUnRead'){
      this.unReadCallBack = callback
      this.menu = obj
    }else if(type == 'profileUnRead'){
      this.profileUnReadCallBack = callback
      this.profile = obj
    }else if(type == 'loginSuccess'){
      this.loginSuccess = callback
      this.campus = obj
    }
  },
  globalData:{
    openId:null,
    userInfo: null,
    sessionId:null,
    active:0,
    
  },
  login:function(phoneCallBack){
    if(phoneCallBack){
      this.onPhoneCallBack = function(complete){
        phoneCallBack(complete);
      }
    }
    let that = this
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if(res.errMsg == 'login:ok'){
            let code = res.code;
            // 获取用户信息
            wx.getSetting({
              success: res => {
                if (res.authSetting['scope.userInfo']) {
                  wx.getUserInfo({
                    success: res => {
                      that.decodeUserInfo(res.encryptedData,res.iv,code,phoneCallBack);
                    },
                    fail: res => {
                      wx.showModal({
                        title: '您拒绝了请求,不能正常使用小程序',
                        icon: 'error',
                        duration: 2000
                      });
                    }
                  })
                }else{//新增游客信息
                  let _url = req.actions.ym+"customer/addTourist";
                  let that = this;
                  utils.myResquest({code:code},_url,function(res){
                    if(res.data.code == 200){
                      //that.globalData.sessionId = res.data.content.sessionId;
                      that.globalData.openId = res.data.content.openid;
                      that.globalData.userInfo = res.data.content.userInfo;
                      wx.setStorageSync("sessionKey",res.data.content.sessionKey)
                      wx.setStorageSync("customerId",res.data.content.userInfo.id)
                      if(phoneCallBack){
                        that.onPhoneCallBack('complete')
                      }
                      that.loginSuccess(that.campus.page,that.campus.type)
                    }
                  });
                }
              }
            })
          }else{
            wx.showToast({title: '登录失败'})
          }
      },
      fail: res => {
        wx.showToast({title: '登录失败'})
      }
    })
  },
  decodeUserInfo:function(encryptedData,iv,code,phoneCallBack){
    let r = {encryptedData:encryptedData,iv:iv,code:code}
    let _url = req.actions.ym+"customer/decodeUserInfo";
    let that = this;
    utils.myResquest(r,_url,function(res){
      console.log("decodeUserInfo==>"+JSON.stringify(res));
      that.globalData.userInfo = res.data.userInfo;
      if(that.globalData.userInfo.img){
        console.log("that.globalData.userInfo.img->"+res.data.userInfo)
        that.globalData.userInfo.img = res.data.userInfo.img
        console.log("that.globalData.userInfo.img->"+that.globalData.userInfo.img)
      } 
      if(that.globalData.userInfo.if_anonymous){
        if(that.globalData.userInfo.if_anonymous == '1'){
          that.globalData.userInfo.ifAnonymous = true
        }else{
          that.globalData.userInfo.ifAnonymous = false
        }
      } 
      that.globalData.userInfo.openId = res.data.userInfo.openid
      that.globalData.openId = res.data.userInfo.openid
      //that.globalData.sessionId = res.data.userInfo.openid;
      wx.setStorageSync("customerId",res.data.userInfo.id)
      wx.setStorageSync("sessionKey",res.data.sessionKey)
      if(phoneCallBack){
        that.onPhoneCallBack('complete')
      }
      console.log("res.data.userInfo.openid==>"+res.data.userInfo.openid);
    });
  },
  
  getSystemInfo: function () {
    let t = this;
    wx.getSystemInfo({success: function (res) {
      t.globalData.systemInfo = res;}});
  },
  onShow(){
    
  }
})